package com.xixiake.activity;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.xixiake.R;
import com.xixiake.net.BaseInput;
import com.xixiake.net.GsonRequest;
import com.xixiake.net.NetClient;
import com.xixiake.net.record.LoginRecord;
import com.xixiake.net.record.UserInfoRecord;
import com.xixiake.utils.Constant;
import com.xixiake.utils.IntentUtil;
import com.xixiake.utils.SharePerferenceUtil;
import com.xixiake.utils.ToastUtil;
import com.xixiake.utils.VerityUtils;

/**
 * Created by c-wanghengli on 2017/5/13.
 */
public class LoginActivity extends BaseActivity implements View.OnClickListener {

    private static final String TAG = "LoginActivity";

    private TextView mTitleLeftTv;
    private EditText mPhoneEditText;
    private EditText mPasswordEditText;
    private Button mOkButton;
    private Button mRegisterBt;
    private TextView mForgetPasswordTv;
    private ImageView mIvWeiXinLogin;
    private LinearLayout own_login_ll_rootlayout;

    private String mPhoneNo;
    private String mPassword;
    private int mErrorCode;
    private String mErrorDec;
    private int mUserid;
    private String mAccesstoken;
    private Long mExpires;
    private String mRefreshtoken;
    private String mType;
    private String mClient;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.own_login);
        initView();
        initEvent();
    }


    private void initView() {
        own_login_ll_rootlayout = (LinearLayout) findViewById(R.id.own_login_ll_layout);
       // mTitleLeftTv = (TextView) findViewById(R.id.title_left_txt_view);
        mPhoneEditText = (EditText) findViewById(R.id.own_login_edit_phone);
        mPasswordEditText = (EditText) findViewById(R.id.own_login_edit_password);
        mOkButton = (Button) findViewById(R.id.own_login_button_oklogin);
        mRegisterBt = (Button) findViewById(R.id.own_login_button_register);
        mForgetPasswordTv = (TextView) findViewById(R.id.own_login_forget);
        mIvWeiXinLogin = (ImageView) findViewById(R.id.own_login_weixin_iv);
    }

    private void initEvent() {

       // mTitleLeftTv.setOnClickListener(this);
        mPhoneEditText.addTextChangedListener(new TextWatcherListener(mPhoneEditText, mPasswordEditText, mOkButton));
        mPasswordEditText.addTextChangedListener(new TextWatcherListener(mPhoneEditText, mPasswordEditText, mOkButton));
        mOkButton.setOnClickListener(this);
        mRegisterBt.setOnClickListener(this);
        mForgetPasswordTv.setOnClickListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    public void onClick(View view) {

        switch (view.getId()){
            case R.id.own_login_button_oklogin:
                mPhoneNo = mPhoneEditText.getText().toString().trim();
                mPassword = mPasswordEditText.getText().toString().trim();
                if(!VerityUtils.verityPhoneNo(mPhoneNo) || !VerityUtils.verifyPassword(mPassword)){
                    ToastUtil.show("用户名或密码有误",Toast.LENGTH_SHORT);
                    return;
                }
                mOkButton.setEnabled(false);
                mOkButton.setText("登录中...");
                requestForLogin();
                break;
            case R.id.own_login_button_register:       // 注册
                IntentUtil.startActivity(this, RegisterActivity.class);
                break;
        }
    }

    private void requestForLogin() {
        BaseInput<LoginRecord> input = LoginRecord.Input.buildInput(mPhoneNo,mPassword);
        GsonRequest<LoginRecord> request = new GsonRequest<>(input, new Response.Listener<LoginRecord>() {
            @Override
            public void onResponse(LoginRecord response) {
                mErrorCode = response.errorCode;
                if(0 == mErrorCode){ //登录成功
                    mAccesstoken = response.data.accesstoken;
                    mClient = response.data.client;
                    mExpires = response.data.expires;
                    mRefreshtoken = response.data.refreshtoken;
                    mUserid = response.data.userid;
                    mType = response.data.type;
                    // 保存到本地
                    SharePerferenceUtil.putInt(Constant.USERID, mUserid);
                    SharePerferenceUtil.putString(Constant.ACCESSTOKEN, mAccesstoken);
                    SharePerferenceUtil.putString(Constant.REFRESHTOKEN, mRefreshtoken);
                    SharePerferenceUtil.putLong(Constant.EXPIRES, mExpires);
                    SharePerferenceUtil.putString(Constant.CLIENT, mClient);
                    SharePerferenceUtil.putString(Constant.TYPE, mType);
                    SharePerferenceUtil.putString(Constant.PHONENO, mPhoneNo);
                    SharePerferenceUtil.putString(Constant.PASSWORD, mPassword);
                    requestForUserInfo();
                }else{
                    mOkButton.setEnabled(true);
                    mOkButton.setText("登录");
                    ToastUtil.show(response.errorMsg,Toast.LENGTH_SHORT);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                mOkButton.setEnabled(true);
                mOkButton.setText("登录");
                ToastUtil.show("登录失败，请检查网络",Toast.LENGTH_SHORT);
            }
        });
        NetClient.request(request);

    }

    private void requestForUserInfo() {
        BaseInput<UserInfoRecord> input = UserInfoRecord.Input.buildInput();
        GsonRequest<UserInfoRecord> request = new GsonRequest<>(input, new Response.Listener<UserInfoRecord>() {
            @Override
            public void onResponse(UserInfoRecord response) {
                if(response.errorCode == 0){
                    SharePerferenceUtil.putString(Constant.USER_HEADERURL,  response.data.userheader);
                    SharePerferenceUtil.putString(Constant.USERNAME, response.data.username);
                    SharePerferenceUtil.putString(Constant.USERGENDER, response.data.usergender);
                    SharePerferenceUtil.putString(Constant.LOGINID,  response.data.loginid);
                    ToastUtil.show("登录成功",Toast.LENGTH_SHORT);
                    //todo 跳转问题未解决
                }else if(response.errorCode == 1100){

                }else{
                    ToastUtil.show(response.errorMsg,Toast.LENGTH_SHORT);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                 ToastUtil.show("请检查网络是否连接",Toast.LENGTH_SHORT);
            }
        });
        NetClient.request(request);
    }

    public class TextWatcherListener implements TextWatcher {

        private EditText editText1;
        private EditText editText2;
        private Button button;

        public TextWatcherListener(EditText editText1, EditText editText2, Button button){
            this.editText1 = editText1;
            this.editText2 = editText2;
            this.button = button;
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (editText1.length() == 11 & editText2.length() >= 6) {
                button.setEnabled(true);
            } else {
                button.setEnabled(false);
            }
        }
    }
}
